<template>
  <div class="details">
    <ContentWrap v-loading="isLoading">
      <List ref="list" :mode="amendData" :column="4" sep="：" label-width="100" default-value="--">
        <ListItem label="购买渠道" dict-type-code="PURCHASE_CHANNEL" :value="detailObj.buyChannel" />
        <ListItem label="工单编号" :value="detailObj.workOrderCode ? detailObj.workOrderCode : '--'" />
        <ListItem label="工单状态" :value="detailObj.workOrderStateName" />
        <ListItem label="派单接收情况">
          {{ detailObj.dispatchReceiveState || '未派单' }}
          <ReceiverDetail type="dispatch" :order-id="detailObj.id" style="display: inline-block;width: auto;"></ReceiverDetail>
        </ListItem>
        <ListItem label="抄送接收情况">
          {{ detailObj.ccReceiveState || '未抄送' }}
          <ReceiverDetail type="cc" :order-id="detailObj.id" style="display: inline-block;width: auto;"></ReceiverDetail>
        </ListItem>
        <ListItem label="创建人" :value="detailObj.createrName?`${detailObj.createrName}(${detailObj.createBy})${detailObj.createByPlatformNo?' - ' + detailObj.createByPlatformNo:''}`:''" />
        <ListItem label="创建时间" :value="detailObj.createTime ? detailObj.createTime : '--'" />
        <ListItem label="联系人" :value="detailObj.contactName" />
        <ListItem label="联系电话" :value="detailObj.contactPhone" :span="24/4*2">
          <span v-if="detailObj.contactPhone" slot="icon" style="margin-left: 10px;color:#00926d;">
            <svg-icon icon-class="shouji-solid" style="cursor:pointer;" @click="contactTpSms(detailObj.contactPhone)"></svg-icon>
            <!-- <SvgIcon icon-class="dianhuaboda-solid" style="cursor:pointer;" @click.native.stop="callOutHandle(detailObj.contactPhone)"></SvgIcon> -->
            <Button type="primary" @click="callOutHandle(detailObj.contactPhone)">外呼</Button>
            <SecondDial :record-id="recordId" style="margin-left:5px"></SecondDial>
          </span>
        </ListItem>
        <ListItem label="会员等级" :value="detailObj.level" />
        <ListItem v-if="detailObj.buyChannel==='1'" label="顾客ID" :value="detailObj.nickname" />
        <ListItem v-if="detailObj.buyChannel==='1'" label="电商平台" :value="detailObj.onlinePlatformName || '--'" />
        <ListItem v-if="detailObj.buyChannel==='1'" label="电商店铺" :value="detailObj.onlineShopName || '--'" />
        <ListItem label="平台订单号" :value="detailObj.orderCode" />
        <ListItem label="电商单号" :value="detailObj.ecOrderNumber" />
        <ListItem v-if="detailObj.buyChannel==='1'" label="下单时间" :value="detailObj.orderTime ? detailObj.orderTime : '--'" />
        <ListItem v-if="detailObj.buyChannel==='1'" label="预约送货时间" :value="deliveryTime || '--'" />
        <ListItem v-if="detailObj.buyChannel==='1'" label="配送方式" dict-type-code="CC_DELIVERY_TYPE" :value="detailObj.deliveryMethod" />
        <ListItem label="省" :value="detailObj.provinceName" />
        <ListItem label="市" :value="detailObj.cityName" />
        <ListItem label="区/县" :value="detailObj.countyName" />
        <ListItem label="街道" :value="detailObj.streetName" />
        <ListItem label="详细地址" :span="24" :value="detailObj.detailAddress" />
        <ListItem label="联系渠道" :value="detailObj.channelTypeName" />
        <ListItem label="一级业务类型" :value="detailObj.businessType1Name || '--'" />
        <ListItem label="二级业务类型" :value="detailObj.businessType2Name || '--'" />
        <template v-if="repairsReasonRequired">
          <ListItem
            v-if="[2, '2'].includes(detailObj.workOrderState)"
            key="repairsReason"
            prop="repairsReason"
            label="报修原因"
            :rules="[
              { required: repairsReasonRequired, validator: (r,v,c)=>{
                if(!repairsReasonRequired){
                  c()
                  return
                }
                if(!v||v.length===0){
                  c('请选择报修原因')
                } else {
                  c()
                }
              }, trigger: 'change' }
            ]"
          >
            <CustomDictSelect
              placeholder="请选择"
              dict-type-code="REPAIR_REASON"
              bind-name="dictName"
              bind-value="dictCode"
              filterable
              :echo-value.sync="amendData.repairsReason"
              multiple
            ></CustomDictSelect>
          </ListItem>
          <ListItem v-else label="报修原因" dict-type-code="REPAIR_REASON" :value="detailObj.repairsReason" />
        </template>
        <!--
          服务费类型显示条件：
          当一级业务类型为咨询(1)，二级业务类型为服务费(13);
          当一级业务类型为投诉/纠纷(2)，二级业务类型为服务费(13)时;
          当赔付原因为服务费(4)时
        -->
        <ListItem
          v-if="
            ([1,2].includes(Number(detailObj.businessType1 || 0)) && Number(detailObj.businessType2 || 0) === 13 ) ||
              (amendData.compensationCause && (amendData.compensationCause.includes(4) || amendData.compensationCause.includes('4')))
          "
          label="服务费类型"
          dict-type-code="SERVICE_FEE_TYPE"
          :value="detailObj.serviceFeeType"
        />
        <!--
          费用类型 条件：
          当一级业务类型为咨询(1)，二级业务类型为费用常规(14)时;
          当一级业务类型为投诉/纠纷(2)，二级业务类型为费用常规(14)时;
          当一级业务类型为业务办理(3)，二级业务类型为费用常规(14)时;
        -->
        <ListItem
          v-if="[1,2,3].includes(Number(detailObj.businessType1 || 0)) && Number(detailObj.businessType2 || 0) === 14 "
          label="费用类型"
          dict-type-code="EXPENSE_TYPE"
          :value="detailObj.feeType"
        />
        <!--
          赔付原因：条件
          当一级业务类型为咨询(1)，二级业务类型为费用赔付(15)时;
          当一级业务类型为投诉/纠纷(2)，二级业务类型为费用赔付(15)时;
          当一级业务类型为业务办理(3)，二级业务类型为费用赔付(15)时;
          当处理页面的处理方案选择【费用赔付(2)】时
        -->
        <ListItem
          v-if="([1,2,3, '1','2','3'].includes(Number(detailObj.businessType1 || 0)) && Number(detailObj.businessType2 || 0) === 15 )||
            (amendData.handleScheme && (amendData.handleScheme.includes(2) || amendData.handleScheme.includes('2')))"
          label="赔付原因"
          dict-type-code="COMPENSATION_REASON"
          :value="detailObj.compensationCause"
          prop="compensationCause"
          :rules="[
            {
              required: compensationCauseIsRequired,
              validator: (r,v,c)=>{
                if(!compensationCauseIsRequired){
                  c()
                  return
                }
                if(v && v.length>0){
                  c()
                } else{
                  c('请选择赔付原因')
                }
              },
              trigger:'change'
            }
          ]"
        >
          <template v-if="Number(detailObj.workOrderState) !== 3">
            <CustomDictSelect
              placeholder="请选择"
              dict-type-code="COMPENSATION_REASON"
              bind-name="dictName"
              bind-value="dictCode"
              multiple
              collapse-tags
              filterable
              :echo-value.sync="amendData.compensationCause"
              :def-value="[]"
            ></CustomDictSelect>
          </template>
        </ListItem>

        <!--
          发票子业务 条件：
          当一级业务类型为咨询(1)，二级业务类型为发票(16)时;
          当一级业务类型为业务办理(3)，二级业务类型为发票(16)时;
        -->
        <ListItem
          v-if="[1,3].includes(Number(detailObj.businessType1 || 0)) && Number(detailObj.businessType2 || 0) === 16"
          label="发票子业务"
          dict-type-code="INVOICE_SUB_SERVICE"
          :value="detailObj.invoiceSubBusiness"
        />
        <ListItem
          v-if="Number(detailObj.businessType1 || 0)===2"
          label="投诉原因"
          dict-type-code="COMPLAINTS_REASON"
          :value="detailObj.complaintCause"
          prop="complaintCause"
          :rules="[
            {
              required: Number(detailObj.businessType1) === 2 && Number(detailObj.businessType2 || 0) !== 44,
              validator: (r,v,c)=>{
                if (Number(detailObj.businessType1) === 2 && Number(detailObj.businessType2 || 0) !== 44) {
                  if (!amendData.complaintCause || amendData.complaintCause.length === 0) {
                    c('请选择投诉原因')
                    return
                  }
                }
                c()
              },
              trigger: 'change'
            }
          ]"
        >
          <!--
              当一级业务类型为投诉/纠纷(2)时; 不同二级业务类型，投诉原因值列不同
              当一级业务类型为投诉/纠纷(2)时，投诉原因、投诉类型为必选 (二级业务类型 为 44 产品质量时 不必选 )
          -->
          <template v-if="Number(detailObj.workOrderState) !== 3">
            <el-select
              v-model="amendData.complaintCause"
              multiple
              filterable
              clearable
              collapse-tags
              @clear="amendData.complaintCause = []"
            >
              <el-option
                v-for="(list, index) of complaintCauseOption"
                :key="index"
                :value="list.dictCode"
                :label="list.dictName"
              />
            </el-select>
          </template>
        </ListItem>
        <!--
          当一级业务类型为投诉/纠纷(2)，二级业务类型为服务态度(23)时展示此字段
        -->
        <ListItem
          v-if="Number(detailObj.businessType1 || 0)===2 && Number(detailObj.businessType2 || 0)===23 "
          label="被投诉对象"
          dict-type-code="OBJECT_OF_COMPLAINT"
          :value="detailObj.complaintObject"
        />
        <!--
          顾客不认可原因 条件：
          当【投诉原因】为“顾客不认可处理方案导致(57)”时
        -->
        <ListItem
          v-if="detailObj.complaintCause && (detailObj.complaintCause.includes(57) || detailObj.complaintCause.includes('57'))"
          label="顾客不认可原因"
          dict-type-code="CUSTOMER_DISAGREE_REASON"
          :value="detailObj.customerDisapprovalCause"
        />

        <ListItem
          v-if="Number(detailObj.businessType1 || 0)===2"
          label="投诉类型"
          dict-type-code="COMPLAINTS_TYPE"
          :value="detailObj.complaintType"
          prop="complaintType"
          :rules="[
            {
              required: Number(detailObj.businessType1) === 2,
              message: '请选择投诉类型',
              trigger:'change'
            }
          ]"
        >
          <!--
            投诉类型展示条件：
            当【一级业务类型】为“投诉/纠纷”(2)时
            当一级业务类型为投诉/纠纷(2)时，投诉原因、投诉类型为必选
          -->
          <template v-if="Number(detailObj.workOrderState) !== 3">
            <CustomDictSelect
              placeholder="请选择"
              dict-type-code="COMPLAINTS_TYPE"
              bind-name="dictName"
              bind-value="dictCode"
              filterable
              :echo-value.sync="amendData.complaintType"
            ></CustomDictSelect>
          </template>
        </ListItem>
        <ListItem v-if="!showJoinIn" label="产品问题" dict-type-code="PRODUCT_PROBLEM" :value="detailObj.productProblem" />
        <!--
          运损类型 展示条件：
          【产品问题】为运损(5)时才展示此字段
        -->
        <!-- v-if="detailObj.repairsReason && (detailObj.repairsReason.includes(7) || detailObj.repairsReason.includes('7'))" -->
        <ListItem
          v-if="detailObj.transportationLossType"
          label="运损类型"
          dict-type-code="TRANSPORT_DAMAGE_TYPE"
          :value="detailObj.transportationLossType"
        />
        <ListItem v-if="!showJoinIn" label="产品类型" :value="detailObj.productTypeName" />
        <ListItem v-if="!showJoinIn" label="功能空间" :value="detailObj.functionalSpaceName" />
        <ListItem v-if="!showJoinIn" label="产品品类" :value="detailObj.productCategoryName" />
        <ListItem v-if="detailObj.productMode" label="产品型号" :value="detailObj.productMode" />
        <ListItem v-if="detailObj.productCode" label="产品编码" :value="detailObj.productCode" />
        <ListItem v-if="detailObj.productName" label="产品名称" :value="detailObj.productName" />

        <ListItem
          v-if="Number(detailObj.workOrderState) === 3"
          label="业务部门"
          dict-type-code="RESPONSIBLE_DEPARTMENT"
          :value="detailObj.bpmDeptCode"
        />
        <ListItem v-else label="业务部门">
          <CustomDictSelect
            placeholder="请选择"
            dict-type-code="RESPONSIBLE_DEPARTMENT"
            bind-name="dictName"
            bind-value="dictCode"
            filterable
            :echo-value.sync="amendData.bpmDeptCode"
            :echo-name.sync="amendData.bpmDeptName"
          ></CustomDictSelect>
        </ListItem>

        <!-- 加盟信息 -->
        <template v-if="showJoinIn">
          <ListItem
            label="是否有店面"
            dict-type-code="ISOWN"
            :value="detailObj.hasShop"
          />
          <ListItem label="店面总面积" :value="detailObj.shopArea" />
          <ListItem
            label="意向经营业务"
            dict-type-code="BIZ_TYPE"
            :value="detailObj.bizType"
            app-code="slm"
          />
          <ListItem
            label="意向客户分类"
            dict-type-code="CTM_TOBE_CUSTOMER_TYPE"
            :value="detailObj.potentialType"
            app-code="slm"
          />
        </template>

        <!-- <ListItem :span="24">
          <Title slot="content" class="custom-title" title="来电明细" />
        </ListItem>
        <ListItem class="call-detail" :span="23" :value="detailObj.callContent">
          {{ detailObj.callContent }}
        </ListItem> -->
        <ListItem :span="24" label="来电明细" :value="detailObj.callContent" />
        <!-- <ListItem :span="24">
          <Title slot="content" class="custom-title" title="客服意见" />
        </ListItem>
        <ListItem class="call-detail" :span="23" :value="detailObj.customerServiceOpinion">
          {{ detailObj.customerServiceOpinion }}
        </ListItem> -->
        <ListItem :span="24" label="客服意见" :value="detailObj.customerServiceOpinion" />

        <ListItem label="责任部门" :value="detailObj.receiveDeptNames" />

        <ListItem label="办事处" :value="detailObj.officeName">
          <!-- <SearchSelectPicker
            url="/call-center/api/v1/mscInfo/office/ref/page"
            :disabled="detailObj.workOrderState === 3"
            placeholder="请选择"
            lable-name="name"
            value-name="code"
            method="get"
            :value.sync="amendData.officeCode"
            :lable.sync="amendData.officeName"
            @selectChange="resetDisName"
          ></SearchSelectPicker> -->
        </ListItem>
        <ListItem label="经销商" :value="detailObj.disName">
          <!-- <SearchSelectPicker
            :disabled="detailObj.workOrderState === 3"
            url="/call-center/api/v1/mscInfo/dealer/ref/page"
            method="get"
            placeholder="请选择经销商"
            :params="{query:{officeCode:amendData.officeCode},type:0}"
            lable-name="name"
            value-name="code"
            custom-name="codeOrName"
            :parent-id="amendData.officeCode"
            :value.sync="amendData.disCode"
            :lable.sync="amendData.disName"
            :current-id.sync="amendData.disId"
            clearable
            @selectChange="disSelectChange"
          ></SearchSelectPicker> -->
        </ListItem>
        <ListItem label="门店" :value="detailObj.shopName">
          <!-- <SearchSelectPicker
            :disabled="detailObj.workOrderState === 3"
            url="/call-center/api/v1/mscInfo/shop/page"
            placeholder="请选择"
            lable-name="shopName"
            value-name="shopCode"
            custom-name="customerName"
            :remote="false"
            :params="{query:{businessStatus: '1,2,6',status:1,customerName: amendData.disName},type:1}"
            :must-pid="true"
            :parent-id="amendData.disName"
            :value.sync="amendData.shopCode"
            :lable.sync="amendData.shopName"
            @selectChange="selectChange"
          ></SearchSelectPicker> -->
        </ListItem>
        <ListItem label="商家回复" dict-type-code="CUSTOMER_APPLY_STATUS" :value="detailObj.customerApplyStatus" />
        <ListItem class="afterCall" label="售后联系人电话" :value="detailObj.afterSalesCall">
          <span v-if="detailObj.afterSalesCall" slot="icon" style="margin-left: 10px;color:#00926d;">
            <svg-icon icon-class="shouji-solid" style="cursor:pointer;" @click="toSms(detailObj.afterSalesCall)"></svg-icon>
            <SvgIcon
              slot="icon"
              icon-class="dianhuaboda-solid"
              style="margin-left: 10px;color:#00926d;cursor:pointer;"
              @click.native.stop="callOutHandle(detailObj.afterSalesCall)"
            ></SvgIcon>
          </span>
          <!-- <el-autocomplete
            v-model="amendData.afterSalesCall"
            placeholder="请输入售后联系人电话"
            :disabled="detailObj.workOrderState === 3"
            popper-class="my-autocomplete"
            :popper-append-to-body="false"
            clearable
            :fetch-suggestions="afterCallSearchAsync"
          >
            <template slot-scope="{ item }">
              <div class="tel" style="font-size: 12px">{{ item.value }}</div>
              <span class="name">{{ item.name }}</span>
            </template>
            <template slot="append">
              <svg-icon icon-class="shouji-solid" class="sms" @click="toSms(amendData)"></svg-icon>
              <SvgIcon icon-class="dianhuaboda-solid" style="color:#00926d;cursor:pointer;" @click.native.stop="callOutHandle(amendData.afterSalesCall)"></SvgIcon>
            </template>
          </el-autocomplete> -->
        </ListItem>
        <ListItem
          prop="urgencyDegree"
          label="紧急程度"
          :rules="[
            {
              required: true,
              message: '请选择紧急程度',
              trigger:'change'
            }
          ]"
        >
          <CustomDictSelect
            :disabled="detailObj.workOrderState === 3"
            dict-type-code="URGENCY_DEGREE"
            bind-name="dictName"
            bind-value="dictCode"
            :echo-value.sync="amendData.urgencyDegree"
          ></CustomDictSelect>
        </ListItem>
        <ListItem
          v-if="Number(amendData.urgencyDegree || 0) === 2 || Number(amendData.urgencyDegree || 0) === 3"
          prop="urgencyCause"
          label="紧急原因备注"
          :rules="[
            {
              required: true,
              message: '请输入紧急原因备注',
              trigger:'change'
            }
          ]"
        >
          <el-input v-model="amendData.urgencyCause" placeholder="请输入" :disabled="detailObj.workOrderState === 3" />
        </ListItem>
        <ListItem label="是否超期" :value="Number(detailObj.isOverdue) === 1 ? '超期' : Number(detailObj.isOverdue) === 0 ? '未超期' : '--'" />
        <ListItem
          v-if="Number(detailObj.isOverdue) === 1"
          prop="overdueReason"
          label="超期原因"
          :rules="[
            {
              required: true,
              message: '请选择超期原因',
              trigger:'change'
            }
          ]"
        >
          <CustomDictSelect
            :disabled="detailObj.workOrderState === 3"
            dict-type-code="OVERDUE_REASON"
            bind-name="dictName"
            bind-value="dictCode"
            :echo-value.sync="amendData.overdueReason"
          ></CustomDictSelect>
        </ListItem>
        <ListItem label="超时工单" :value="Number(detailObj.isTimeoutOrder) === 1 ? '是' : Number(detailObj.isTimeoutOrder) === 0 ? '否' : '--'" />
        <ListItem label="是否超时" :value="Number(detailObj.isTimeout) === 1 ? '超时' : Number(detailObj.isTimeout) === 0 ? '未超时' : '--'" />
        <ListItem
          v-if="Number(detailObj.isTimeoutOrder) === 1"
          prop="overtimeReason"
          label="超时原因"
          :rules="[
            {
              required: true,
              message: '请选择超时原因',
              trigger:'change'
            }
          ]"
        >
          <CustomDictSelect
            :disabled="detailObj.workOrderState === 3"
            dict-type-code="OVER_TIME_REASON"
            bind-name="dictName"
            bind-value="dictCode"
            :echo-value.sync="amendData.overtimeReason"
          ></CustomDictSelect>
        </ListItem>

        <!-- 处理截止时间只限控制办事处和经销商 -->
        <ListItem v-if="detailObj.workOrderState === 3" label="处理截止时间" :value="detailObj.processingDeadline || '--'" />
        <ListItem
          v-else
          label="处理截止时间"
          prop="processingDeadline"
          :rules="[{required: isEC, message: '请选择处理截止时间', trigger: 'change'}]"
        >
          <el-date-picker
            v-model="amendData.processingDeadline"
            type="datetime"
            clearable
            placeholder="选择日期时间"
            align="right"
            value-format="yyyy-MM-dd HH:mm:ss"
            default-time="21:00:00"
            :picker-options="pickerOptions"
            :disabled="detailObj.workOrderState === 3"
            popper-class="noneTick"
          />
        </ListItem>
        <ListItem label="处理时效" :value="Number(detailObj.timeoutReason) === 1 ? '不及时' : Number(detailObj.timeoutReason) === 0 ? '及时' : '--'" />
        <ListItem
          label="处理人"
          :value="detailObj.handlerList instanceof Array ? detailObj.handlerList.map(e=>`${e.handlerName}(${e.handler})`).join(','):''"
        />

        <!--:disabled="detailObj.workOrderState === 3"-->
        <!-- <ListItem label="处理人">
          {{ amendData.nextHandler }}
          <SearchSelectPicker
            url="/call-center/api/v1/staffInfo/page"
            lable-name="staffName"
            value-name="accountNo"
            disabled
            :value.sync="amendData.nextHandler"
            :lable.sync="amendData.nextHandlerName"
            :platform-no.sync="amendData.nextHandlerPlatformNo"
          ></SearchSelectPicker>
        </ListItem> -->
        <ListItem
          v-if="detailObj.workOrderState !== 3"
          label="处理方案"
          prop="handleScheme"
          :rules="[
            { required: true,
              message: '请选择处理方案',
              trigger: 'change'
            },
            { required: true,
              validator: (r,v,c)=>{
                if(!v || v.length===0){
                  c('请选择处理方案')
                } else {
                  c()
                }
              },
              trigger: 'change'
            }
          ]"
        >
          <CustomDictSelect
            dict-type-code="PROCESS_METHOD"
            bind-name="dictName"
            bind-value="dictCode"
            multiple
            collapse-tags
            filterable
            :echo-value.sync="amendData.handleScheme"
            :filter-handle="filterHandleScheme"
            :def-value="[]"
          ></CustomDictSelect>
        </ListItem>
        <ListItem v-else label="处理方案" dict-type-code="PROCESS_METHOD" :value="amendData.handleScheme" />
        <ListItem
          v-if="([1, 3, '1', '3'].includes(detailObj.businessType1) && [18, 19, '18', '19'].includes(detailObj.businessType2)) || (amendData.handleScheme && amendData.handleScheme.some(e => [9, 10, 14, '9', '10', '14'].includes(e)))"
          label="退/换货原因"
          dict-type-code="RETURN_REPLACEMENT_REASON"
          :value="detailObj.returnsCause"
          prop="returnsCause"
          :rules="[
            {
              required: Number(detailObj.workOrderState) !== 3,
              message: '请选择退/换货原因',
              trigger:'change'
            }
          ]"
        >
          <!--
              1.当一级业务类型为咨询(1)，二级业务类型为退货(18)时，展示该字段；
              2.当一级业务类型为咨询(1)，二级业务类型为换货(19)时，展示该字段；
              3.当一级业务类型为业务办理(3)，二级业务类型为退货(18)时，展示该字段；
              4.当一级业务类型为业务办理(3)，二级业务类型为换货(19)时，展示该字段；
            -->
          <template v-if="Number(detailObj.workOrderState) !== 3">
            <CustomDictSelect
              placeholder="请选择"
              dict-type-code="RETURN_REPLACEMENT_REASON"
              bind-name="dictName"
              bind-value="dictCode"
              filterable
              :echo-value.sync="amendData.returnsCause"
            ></CustomDictSelect>
          </template>
        </ListItem>
        <template
          v-if="
            ([1,2,3].includes(Number(detailObj.businessType1 || 0)) && [14,15].includes(Number(detailObj.businessType2 || 0))) || (
              amendData.handleScheme &&
              (amendData.handleScheme.includes(2) || amendData.handleScheme.includes('2') ||
              amendData.handleScheme.includes(3) || amendData.handleScheme.includes('3')||
              amendData.handleScheme.includes(11) || amendData.handleScheme.includes('11')||
              amendData.handleScheme.includes(12) || amendData.handleScheme.includes('12'))
            )
          "
        >
          <ListItem
            v-if="detailObj.workOrderState !== 3"
            label="支付方式"
          ><!--
            支付方式展示条件：
              1.当一级业务类型为咨询(1)，二级业务类型为费用常规(14)时，展示该字段；
              2.当一级业务类型为投诉/纠纷(2)，二级业务类型为费用常规(14)时，展示该字段；
              3.当一级业务类型为业务办理(3)，二级业务类型为费用常规(14)时，展示该字段；
              4.当一级业务类型为咨询(1)，二级业务类型为费用赔付(15)时，展示该字段；
              5.当一级业务类型为投诉/纠纷(2)，二级业务类型为费用赔付(15)时，展示该字段；
              6.当一级业务类型为业务办理(3)，二级业务类型为费用赔付(15)时，展示该字段；
              7.当处理方案为费用赔付(2)/赠品(3)/退差(11)/退款(12)时，展示该字段。
            -->
            <CustomDictSelect
              dict-type-code="PAYMENT_MODE"
              bind-name="dictName"
              bind-value="dictCode"
              multiple
              collapse-tags
              filterable
              :echo-value.sync="amendData.paymentMode"
              :def-value="[]"
            ></CustomDictSelect>
          </ListItem>
          <ListItem v-else label="支付方式" dict-type-code="PAYMENT_MODE" :value="amendData.paymentMode" />
        </template>
        <ListItem
          v-if="
            ([1,2,3].includes(Number(detailObj.businessType1 || 0)) && Number(detailObj.businessType2 || 0)===15)|| (
              amendData.handleScheme &&
              (amendData.handleScheme.includes(2) || amendData.handleScheme.includes('2') ||
              amendData.handleScheme.includes(11) || amendData.handleScheme.includes('11')||
              amendData.handleScheme.includes(12) || amendData.handleScheme.includes('12'))
            )
          "
          label="赔付金额"
          prop="compensationFee"
          :rules="[
            {
              required: true,
              pattern:/^(([1-9]{1}\d{0,9})|(0{1}))(\.\d{1,2})?$/,
              message: '请输入合法金额，最多两位小数',
              trigger:'change'
            }
          ]"
        >
          <!--
              1.当一级业务类型为咨询(1)，二级业务类型为费用赔付(15)时，展示该字段；
              2.当一级业务类型为投诉/纠纷(2)，二级业务类型为费用赔付(15)时，展示该字段；
              3.当一级业务类型为业务办理(3)，二级业务类型为费用赔付(15)时，展示该字段；
              4.当处理方案为费用赔付(2)/退差(11)/退款(12)时，展示该字段。
            -->
          <el-input v-model="amendData.compensationFee" :disabled="detailObj.workOrderState === 3" :maxlength="10" clearable />
        </ListItem>

        <ListItem
          v-if="(amendData.paymentMode && amendData.paymentMode.some(e=>e===5||e==='5')) || (amendData.handleScheme && amendData.handleScheme.some(e=>e===3||e==='3'))"
          label="赠品名称"
          prop="gift"
          :rules="[
            {
              required: true,
              message: '请输入赠品名称',
              trigger:'change'
            }
          ]"
        >
          <!--
              1.当【支付方式】为赠品(5)时，展示该字段；
              2.手动录入，允许汉字、数字、标点符号
            -->
          <el-input v-model="amendData.gift" :disabled="detailObj.workOrderState === 3" :maxlength="100" clearable />
        </ListItem>

        <template v-if="[1,3].includes(Number(detailObj.businessType1 || 0)) && Number(detailObj.businessType2 || 0) === 22">
          <!-- 1.工单一级业务类型为咨询(1)/业务办理(3)，二级业务类型为送装服务(22)，才展示该板块信息。 -->
          <ListItem :span="24">
            <Title slot="content" class="custom-title" title="送装服务信息" />
          </ListItem>
          <ListItem
            label="送装需求"
            prop="deliveryNeed"
            :rules="[{required: [22,'22'].includes(detailObj.businessType2), message: '请选择送装需求',trigger: 'change'}]"
          >
            <CustomDictSelect
              placeholder="请选择"
              dict-type-code="DELIVERY_INSTALL_DEMAND"
              bind-name="dictName"
              bind-value="dictCode"
              filterable
              :echo-value.sync="amendData.deliveryNeed"
              :disabled="detailObj.workOrderState === 3"
            ></CustomDictSelect>
          </ListItem>
          <ListItem label="预约送装服务时间">
            <el-date-picker
              v-model="amendData.bookingServiceTime"
              type="datetime"
              placeholder="选择预约送装服务时间"
              value-format="yyyy-MM-dd HH:mm:ss"
              :disabled="detailObj.workOrderState === 3"
            />
          </ListItem>
        </template>

        <template v-if="Number(detailObj.businessType1 || 0) === 3 && [18,19,31,32,33].includes(Number(detailObj.businessType2 || 0))">
          <!-- 当一级业务类型为业务办理(3)，二级业务类型为退货(18),换货(19),报修(31)/拆装(33)/保养(32)时，才展示该板块信息。 -->
          <ListItem :span="24">
            <Title slot="content" class="custom-title" title="售后服务信息" />
          </ListItem>
          <ListItem label="服务师傅" :value="detailObj.repairTeacherName || '--'" />
          <ListItem label="师傅号码" :value="detailObj.repairTeacherPhone || '--'" />
          <ListItem label="服务费" :value="detailObj.serviceCharge || '--'" />
          <ListItem label="服务时间" :value="detailObj.repairDate || '--'" />
          <ListItem
            label="维修进度"
            prop="processRate"
            :rules="[{required: isEC, message: '请选择维修进度',trigger: 'change'}]"
          >
            <CustomDictSelect
              :disabled="detailObj.workOrderState === 3"
              dict-type-code="PROCESS_RATE"
              bind-name="dictName"
              bind-value="dictCode"
              :echo-value.sync="amendData.processRate"
            ></CustomDictSelect>
          </ListItem>

          <ListItem
            label="核算二次费用"
            prop="isTwoCheckComputation"
            :rules="[
              {
                required: finishOrderLoading,
                validator: (r,v,c)=> {
                  if(!finishOrderLoading){
                    c()
                    return
                  }
                  if (Number(detailObj.businessType1 || 0) === 3 && [18, 19, 31, 32, 33].includes(Number(detailObj.businessType2 || 0))) {
                    // 属于三方物流(经销商的所属办事处为6006)时,必选
                    if (Number(detailObj.officeCode || 0) === 6006) {
                      if ((amendData.isTwoCheckComputation !== 0 && amendData.isTwoCheckComputation !== '0') && (amendData.isTwoCheckComputation !== 1 && amendData.isTwoCheckComputation !== '1')) {
                        c('请选择核算二次费用')
                        return
                      }
                    }
                  }
                  c()
                },
                trigger: 'change'
              }
            ]"
          >
            <el-select
              v-model="amendData.isTwoCheckComputation"
              placeholder="请选择"
              :disabled="detailObj.workOrderState === 3"
              clearable
              filterable
            >
              <el-option
                v-for="(itcc,i) in YesOrNoList"
                :key="i"
                :value="itcc.dictCode"
                :label="itcc.dictName"
              ></el-option>
            </el-select>
          </ListItem>

          <ListItem label="是否补件超期">
            <el-select
              v-model="amendData.isPatchOverdue"
              placeholder="请选择"
              :disabled="detailObj.workOrderState === 3"
              clearable
            >
              <el-option
                v-for="(itcc,i) in YesOrNoList"
                :key="i"
                :value="itcc.dictCode"
                :label="itcc.dictName"
              ></el-option>
            </el-select>
          </ListItem>
        </template>

        <template v-if="Number(detailObj.businessType2 || 0)===31">
          <!-- 当【二级业务类型】为报修(31)时，展示该字段。 -->
          <ListItem :span="24">
            <Title slot="content" class="custom-title" title="补件列表" />
          </ListItem>

          <ListItem v-if="detailObj.workOrderState !== 3" label="补件单号" :span="8">
            <el-input v-model="patchCode" placeholder="请输入补件单号" clearable />
          </ListItem>
          <ListItem v-if="detailObj.workOrderState !== 3" :span="2">
            <el-button type="primary" @click="handleSearchPatchOrder">确定</el-button>
          </ListItem>
          <ListItem :span="24">
            <PbillList
              v-if="detailObj && detailObj.id"
              ref="billList"
              :readonly="detailObj.workOrderState===3"
              :dis-code="amendData.disCode"
              :patch-code.sync="amendData.patchCode"
              @data-change="billChange"
            ></PbillList>
          </ListItem>

        </template>

        <ListItem :span="24">
          <Title slot="content" class="custom-title" title="产品信息" />
        </ListItem>
        <ListItem :span="24">
          <ShowProductInfoList :table-data="detailObj.productInfoDTOList || []"></ShowProductInfoList>
        </ListItem>
        <template v-if="(detailObj.returnGoodsProcessDTOS || []).length>0">
          <ListItem :span="24">
            <Title slot="content" class="custom-title" title="退货进度">
              <el-button type="primary" @click="handleAudit">客诉审核</el-button>
            </Title>
          </ListItem>
          <ListItem :span="24">
            <ReturnedGoods :table-data="detailObj.returnGoodsProcessDTOS || []"></ReturnedGoods>
          </ListItem>
        </template>

        <ListItem :span="24">
          <Title slot="content" class="custom-title" title="留言信息" />
        </ListItem>
        <ListItem :span="24">
          <el-input v-model="amendData.content" type="textarea" :autosize="{minRows:4}" placeholder="请输入" />
        </ListItem>
        <ListItem :span="24">
          <div slot="content" class="button-container">
            <!-- <DialogUpload
              :on-success="onSuccessHandle"
              multiple
              :destroy="false"
              :on-remove="onRemoveHandle"
              :on-change="onChangeHandle"
              :exist-file-list="annexList"
              :before-remove="onPreRemoveHandle"
              text="附件管理"
              title="附件管理"
            /> -->
            <DialogUpload
              :on-success="onSuccessHandle"
              multiple
              :destroy="false"
              :on-remove="removeHandle"
              :before-remove="beforeRemoveHandle"
              :on-change="onChangeHandle"
              :exist-file-list="annexList"
              text="附件管理"
              title="附件管理"
            />
            <Button v-if="detailObj.customerApplyStatus === '02' && ![3,'3'].includes(detailObj.workOrderState)" type="primary" :disabled="InvalidReturnButton" @click="handlerInvalidReturn">无效退回</Button>
            <!-- 异常上报 -->
            <AbnormalReport
              :button-auth="!bottomAuth.abnormal"
              :carbon-info="detailObj"
              :order-id="detailObj.id"
              :work-order-code="detailObj.workOrderCode"
              :work-order-state="detailObj.workOrderState"
              @on-success="abnormalSuccess"
            />
            <!-- 催办 -->
            <UrgeOrder
              :disabled="detailObj.workOrderState === 3 || bottomAuth.urge"
              :carbon-info="detailObj"
              :enable-open="checkIsOpenUrge"
              @on-success="handleUrgeSuccess"
            ></UrgeOrder>
            <!-- 改派 -->
            <DispachList
              text="改派"
              title="改派"
              :receive="receiveSystem"
              :carbon-info="detailObj"
              :disabled="detailObj.workOrderState === 3 || bottomAuth.receive"
              @update-receive="receiveSinga"
              @on-success="receiveSuccess"
            />
            <!-- 抄送 -->
            <CarbonCopy
              :cc-system="ccSystem"
              :carbon-info="detailObj"
              :bottom-auth="bottomAuth.carbon"
              @on-success="carbonSuccess"
            />

            <Button
              :type="detailObj.workOrderState === 3 ? 'info' : 'primary'"
              :loading="saveLoading"
              :disabled="detailObj.workOrderState === 3 || bottomAuth.save"
              @click="saveOrder"
            >保存</Button>
            <Button type="primary" :loading="submitOrderLoading" :disabled="bottomAuth.submit" @click="submitOrder">提交</Button>
            <Button :type="detailObj.workOrderState === 3 ? 'info' : 'primary'" :disabled="detailObj.workOrderState === 3 || bottomAuth.finish" :loading="finishOrderLoading" @click="finishOrder">完结</Button>
            <Care :amend-data="detailObj" :disabled="bottomAuth.care || detailObj.isCare === 1" text="关怀" title="关怀" @on-success="careSuccess" />
            <Button :type="detailObj.workOrderState !== 3 ? 'info' : 'primary'" :disabled="detailObj.workOrderState !== 3" @click="copyWorkOrder">复制工单</Button>
          </div>
        </ListItem>
        <ListItem :span="24">
          <Title slot="content" class="custom-title order-top" title="工单流水记录" />
        </ListItem>
        <ListItem :span="24">
          <div slot="content" class="order-list">
            <FlowOrder v-for="(f,i) in processingListSort" :key="i" :flow="f" />
          </div>
        </ListItem>
      </List>
    </ContentWrap>
    <CallOut ref="callOut"></CallOut>
  </div>
</template>
<script>
import ContentWrap from '@/components/ContentWrap'
import Title from '@/components/Title'
import Button from '@/components/Button'
import { List, ListItem } from '@/components/List'
import AbnormalReport from '../components/AbnormalReport'
import CarbonCopy from '../components/CarbonCopy'
import DialogUpload from '@/components/Upload/DialogUpload'
import DispachList from '../components/DispachList'
import FlowOrder from '../components/FlowOrder'
import PbillList from '../components/PbillList'
import UrgeOrder from '../components/UrgeOrder'
import ReceiverDetail from '../components/ReceiverDetail'
// import SearchSelectPicker from '@/components/SearchSelectPicker'
import CustomDictSelect from '@/components/CustomDictSelect'
import Care from './components/Care'
import WarnMerchant from './components/WarnMerchant'

import ShowProductInfoList from '../components/ShowProductInfoList'
import ReturnedGoods from '../components/ReturnedGoods'
import SecondDial from '@/views/callBarPage/callOut/components/SecondDial'

import { TCCMap } from '../createOrder/businessType2ComplaintCause' // 二级业务类型=>投诉原因映射数据
import { deepCopy } from '@/utils/'
import { ArrayFormat } from '@/utils/params-format'
import { getShopAfterInfo } from '@/api/shopAfter'
import { getDictByType } from '@/api/dataDict'
import { getWorkOrderByCode, getByIdWorkOrderRecord, postWorkOrderRecord, putFinish, putSubmit, deleteAnnex, invalidReturnApplyStatus, queryDeliveryBySources } from '@/api/workOrder'
import { getOfficeRef, getShopList, getMscInfoShop, getCustomerRefPage, getOfficeDetail, getDealerInfo } from '@/api/mscInfo'
export default {
  name: 'DisposeOrderDetails',
  components: {
    ContentWrap,
    ListItem,
    List,
    Title,
    Button,
    AbnormalReport,
    CarbonCopy,
    DialogUpload,
    DispachList,
    FlowOrder,
    CustomDictSelect,
    // SearchSelectPicker,
    Care,
    ReceiverDetail,
    PbillList,
    UrgeOrder,
    ShowProductInfoList,
    ReturnedGoods,
    SecondDial
  },
  data() {
    return {
      id: '',
      isLoading: true,
      pickerOptions: {
        disabledDate: (time) => {
          return (time.getTime() + 24 * 3600 * 1000) < Date.now()
        }
      },
      officeNameOption: [],
      disNameOption: [],
      shopNameOption: [],
      shopCallTel: [],
      complaintTypeOp: [],
      returnsCauseOp: [],
      urgencyDegreeOp: [],
      overdueReasonOp: [],
      overtimeReasonOp: [],
      handleSchemeOp: [],
      paymentModeOp: [],
      deliveryNeedOp: [],
      processRateOp: [],
      complaintCauseStore: [], // 投诉原因
      YesOrNoList: [
        { dictCode: 1, dictName: '是' },
        { dictCode: 0, dictName: '否' }
      ],
      // 坐席修改的数据
      isEdit: false,
      amendData: {
        id: '',
        workOrderCode: '', // 工单编号
        workOrderState: '', // 工单状态
        contactName: '', // 联系人
        contactPhone: '', // 联系电话

        complaintCause: [], // 投诉原因
        complaintType: '', // 投诉类型
        returnsCause: '', // 退换货原因
        bpmDeptCode: '', // 业务部门
        bpmDeptName: '', // 业务部门名称
        compensationCause: [], // 赔付原因
        repairsReason: [], // 报修原因
        /* officeCode: '', // 办事处编码
        officeName: '', // 办事处
        disId: '', // 经销商ID
        disCode: '', // 经销商编码
        disName: '', // 经销商
        shopCode: '', // 门店编码
        shopName: '', // 门店
        afterSalesCall: '', // 售后联系人电话 */
        urgencyDegree: '', // 紧急程度
        urgencyCause: '', // 紧急原因备注
        overdueReason: '', // 超期原因
        overtimeReason: '', // 超时原因
        processingDeadline: '', // 处理截止时间
        /* nextHandler: '', // 处理人
        nextHandlerName: '', // 处理人名字
        nextHandlerPlatformNo: '', // 处理平台号 */
        handleScheme: [], // 处理方案
        paymentMode: [], // 支付方式
        compensationFee: '', // 赔付金额
        gift: '', // 赠品名称
        deliveryNeed: '', // 送装需求
        bookingServiceTime: '', // 预约送装服务时间
        processRate: '', // 维修进度
        isTwoCheckComputation: '', // 核算二次费用
        isPatchOverdue: 0, // 是否补件超期
        content: '', // 留言信息
        patchCode: ''// 补件单号
      },
      originalData: {}, // 临时存放原始数据
      // 工单流水记录
      flowList: [],
      // 已经存在的附件
      annexList: [],
      imageList: [],
      processingList: [],
      detailObj: {},
      receiveSystem: [], // 指派系统：UIP 办事处， PANDA 经销商， ECO 责任部门
      ccSystem: [], // 抄送系统:UIP 办事处， PANDA 经销商， ECO 责任部门
      saveLoading: false,
      submitOrderLoading: false,
      finishOrderLoading: false,
      urgeLoading: false,
      bottomAuth: {
        save: false,
        urge: false,
        carbon: false,
        submit: false,
        office: false,
        dis: false,
        shop: false,
        finish: false,
        sync: false,
        abnormal: false,
        care: false
      }, // 按钮权限是否禁用：true 禁用，false 可用
      patchCode: '',
      InvalidReturnButton: false, // 是否禁用无效退回按钮
      deliveryInfo: [], // 配送信息
      recordId: '' // 通话记录id
    }
  },
  computed: {
    processingListSort() {
      const list = [...this.processingList]
      return list.sort((f, l) => {
        const fd = new Date(f.createTime).getTime()
        const ld = new Date(l.createTime).getTime()
        return ld - fd
      })
    },
    // 当前可选投诉原因
    complaintCauseOption() {
      const dictCode = this.detailObj.businessType2
      if (!dictCode) return []
      const data = TCCMap[dictCode]
      if (!data || data.length === 0) {
        return
      }
      const options = this.complaintCauseStore.filter(e => {
        return data.includes(Number(e.dictCode || 0))
      })
      return options
    },
    // 是电商
    isEC() {
      return this.detailObj.buyChannel === '1' || this.detailObj.buyChannel === 1
    },
    // 赔付原因是否必填
    compensationCauseIsRequired() {
      return ([3, '3'].includes(this.detailObj.businessType1) && [15, '15'].includes(this.detailObj.businessType2)) || (this.amendData.handleScheme && this.amendData.handleScheme.some(e => e === 2 || e === '2'))
    },
    repairsReasonRequired() {
      return [31, '31'].includes(this.detailObj.businessType2)
    },
    showJoinIn() {
      const { businessType1, businessType2 } = this.detailObj
      return [1, '1'].includes(businessType1) && [6, '6'].includes(businessType2)
    },
    deliveryTime() {
      if (!this.deliveryInfo || this.deliveryInfo.length <= 0) {
        return ''
      }
      const t = []
      const ecOrderNumber = typeof this.detailObj.ecOrderNumber === 'string' ? this.detailObj.ecOrderNumber.split(',') : this.detailObj.ecOrderNumber
      for (const ec of ecOrderNumber) {
        const t1 = this.deliveryInfo.find(e => ec === e.sourceCode)
        if (t1) {
          t.push(t1.deliveryTime)
        }
      }
      return t.join(',')
    }
  },
  watch: {
    amendData: {
      handler(newVal, oldVal) {
        if (JSON.stringify(newVal) !== JSON.stringify(oldVal)) {
          this.isEdit = true
        }
      },
      immediate: false,
      deep: true
    },
    imageList: {
      handler(nv, ov) {
        if (JSON.stringify(nv) !== JSON.stringify(ov)) {
          this.isEdit = true
        }
      },
      immediate: false,
      deep: true
    },
    // 选择经销商同步办事处
    'amendData.disCode': {
      handler(newVal, oldVal) {
        if (newVal !== oldVal && newVal) {
          if (!this.amendData.officeCode) {
            this.findOfficeInfo(newVal)
          }
        }
      },
      immediate: true
    },
    // 维修进度改变时重置补贴金额、补贴原因
    'amendData.processRate': {
      handler(n, o) {
        /* if (n === 11 || n === '11') return
        this.$set(this.amendData, 'subsidyAmount', '0')
        this.$set(this.amendData, 'subsidyReason', '') */
      },
      immediate: true
    }
  },
  created() {
    // if (this.$route.query.id === '' || this.$route.query.id === undefined) {
    //   // this.closeCurrentTag()
    //   this.isLoading = false
    //   return false
    // }
    // this.getOfficeName()
    // this.initCustomerRef()
    const { workOrderNo, id } = this.$route.query
    if (workOrderNo) {
      this.getDisposeOrderDetail(workOrderNo, 'workOrderCode')
    } else if (id) {
      this.getDisposeOrderDetail(id, 'id')
    }
    this.initOptions() // 初始化数据字典值列表
  },
  methods: {
    // 获取经销商对应的办事处
    findOfficeInfo(disCode) {
      getOfficeDetail(disCode).then(res => {
        if (res.success === 1) {
          this.amendData.officeName = res.data.name
          this.amendData.officeCode = res.data.code
        }
      })
    },
    initOptions() {
      this.getDictInfo({ type: 'complaintType', dictTypeCode: 'COMPLAINTS_TYPE' }) // 投诉类类型
      this.getDictInfo({ type: 'returnsCause', dictTypeCode: 'RETURN_REPLACEMENT_REASON' }) // 退/换货原因
      // this.getDictInfo({ type: 'bpmDeptCode', dictTypeCode: 'RESPONSIBLE_DEPARTMENT' }) // 业务部门
      this.getDictInfo({ type: 'compensationCause', dictTypeCode: 'COMPENSATION_REASON' }) // 赔付原因

      this.getDictInfo({ type: 'urgencyDegree', dictTypeCode: 'URGENCY_DEGREE' }) // 紧急程度
      this.getDictInfo({ type: 'overdueReason', dictTypeCode: 'OVERDUE_REASON' }) // 超期原因
      // this.getDictInfo({ type: 'timeoutReason', dictTypeCode: 'TIMEOUT_REASON' }) // 处理时效
      this.getDictInfo({ type: 'overtimeReason', dictTypeCode: 'OVER_TIME_REASON' }) // 超时原因
      this.getDictInfo({ type: 'handleScheme', dictTypeCode: 'PROCESS_METHOD' }) // 处理方案
      this.getDictInfo({ type: 'paymentMode', dictTypeCode: 'PAYMENT_MODE' }) // 支付方式
      this.getDictInfo({ type: 'deliveryNeed', dictTypeCode: 'DELIVERY_INSTALL_DEMAND' }) // 送装需求
      this.getDictInfo({ type: 'processRate', dictTypeCode: 'PROCESS_RATE' }) // 维修进度
      // this.getDictInfo({ type: 'subsidyReason', dictTypeCode: 'SUBSIDY_REASON' })
      this.getDictInfo({ type: 'complaintCause', dictTypeCode: 'COMPLAINTS_REASON' }) // 查询投诉原因值列表
    },

    // 获取数据字典
    getDictInfo({ type, dictTypeCode }) {
      const params = { dictTypeCode: dictTypeCode, appCode: 'call-center', domainCode: 'marketing' }
      getDictByType(params).then(res => {
        const data = res.data || []

        if (type === 'compensationCause') this.compensationCauseOp = data
        if (type === 'complaintType') this.complaintTypeOp = data
        if (type === 'returnsCause') this.returnsCauseOp = data
        // if (type === 'bpmDeptCode') this.bpmDeptOp = data
        if (type === 'urgencyDegree') this.urgencyDegreeOp = data
        if (type === 'overdueReason') this.overdueReasonOp = data
        if (type === 'overtimeReason') this.overtimeReasonOp = data
        if (type === 'handleScheme') this.handleSchemeOp = data
        if (type === 'paymentMode') this.paymentModeOp = data
        if (type === 'deliveryNeed') this.deliveryNeedOp = data
        if (type === 'processRate') this.processRateOp = data
        if (type === 'complaintCause') this.complaintCauseStore = data
      })
    },
    /**
     * 初始化经销商信息
     */
    initCustomerRef() {
      getCustomerRefPage().then(resopnse => {
        if (resopnse.success === 1) {
          this.disNameOption = resopnse.data.records
        }
      })
    },
    /**
     * 获取工单详情
     */
    getDisposeOrderDetail(id, type = 'id') {
      if (id === '') {
        this.closeCurrentTag()
        return
      }
      let ajaxName = getByIdWorkOrderRecord
      if (type === 'workOrderCode') {
        ajaxName = getWorkOrderByCode
      }
      // this.isLoading = true
      ajaxName(id).then(async(res) => {
        if (res.success === 1) {
          const data = { ...res.data }
          this.id = data.id
          data.bpmDeptName = await this.$getDictValue('RESPONSIBLE_DEPARTMENT', data.bpmDeptCode)
          data.channelTypeName = await this.$getDictValue('CHANNEL_TYPE', String(data.channelType))
          data.productTypeName = await this.$getDictValue('PRODUCT_TYPE', String(data.productType))
          data.functionalSpaceName = await this.$getDictValue('FUNCTIONAL_SPACE', String(data.functionalSpace))
          data.productCategoryName = await this.$getDictValue('PRODUCT_CATEGORY', String(data.productCategory))
          data.workOrderStateName = await this.$getDictValue('WORK_ORDER_STATUS', String(data.workOrderState))

          const toStringArr = ['urgencyDegree', 'overdueReason', 'timeoutReason', 'overtimeReason', 'processRate'] // 需转换为字符串的字段
          const multToStringArr = ['serviceFeeType', 'feeType', 'compensationCause', 'complaintCause', 'complaintObject', 'customerDisapprovalCause', 'productProblem', 'handleScheme', 'paymentMode', 'repairsReason'] // 多选值转换为数组的字段
          const numToStrArr = ['businessType1', 'businessType2', 'deliveryMethod'] // 数字转换为字符串
          this.$nextTick(() => {
            Object.keys(this.amendData).forEach(key => {
              if (toStringArr.indexOf(key) !== -1) {
                if (data[key] !== undefined && data[key] !== null && data[key] !== '') {
                  this.$set(this.amendData, key, String(data[key]))
                } else {
                  this.$set(this.amendData, key, '')
                }
              } else if (multToStringArr.indexOf(key) !== -1) {
                let tmpArr = []
                if (data[key] && data[key].length) {
                  tmpArr = data[key].map(v => String(v) || '')
                }
                this.$set(this.amendData, key, tmpArr)
              } else if (numToStrArr.indexOf(key) !== -1) {
                this.$set(this.amendData, key, this.$numToString(data[key]))
              } else {
                this.$set(this.amendData, key, data[key] || '')
              }
            })
            if (data.saveContent) {
              this.amendData.content = `${data.saveContent}${this.amendData.content || ''}`
            }
            this.amendData.isPatchOverdue = Number(data.isPatchOverdue || 0)
          })
          this.$nextTick(() => {
            this.originalData = deepCopy(this.amendData)
          })
          // 获取配送信息
          if (data.ecOrderNumber) {
            this.getDeliveryInfo(data.ecOrderNumber.split(','))
          }
          // createTime
          // this.processingList = (data.processingList || []).reverse()
          this.processingList = data.processingList || []
          if (Array.isArray(data.annexList) && data.annexList.length) {
            this.annexList = data.annexList.map(list => {
              list['name'] = list.fileName
              list['url'] = list.filePath
              return list
            })
          }
          this.getLocalDealerInfo(data.officeCode, data.disCode)
          if (data.shopCode) {
            this.getSalesCall({ shopCode: data.shopCode })
          } else if (data.disCode) {
            this.checkShopNum(data.disCode)
          }
          if (Object.keys(data).indexOf('receiveSystem') !== -1) this.receiveSystem.push(data.receiveSystem)
          if (Object.keys(data).indexOf('ccSystem') !== -1) this.ccSystem.push(data.ccSystem)
          this.$nextTick(() => {
            this.detailObj = data
            this.isLoading = false
          })
        }
      }, () => {
        this.isLoading = false
      })
    },
    // 加载本地经销商
    getLocalDealerInfo(code, disCode) {
      getDealerInfo({ officeCode: code, codeOrName: disCode }).then(res => {
        if (res.success === 1) {
          this.disNameOption = res.data.records
          const obj = res.data.records.find(list => {
            return list.code === disCode
          })
          if (obj === undefined || obj === 'undefined') return
          this.getLocalShopInfo(obj.id)
        }
      })
    },
    // 加载本地门店
    getLocalShopInfo(id) {
      getShopList(id).then(res => {
        if (res.success === 1) this.shopNameOption = res.data
      })
    },
    /**
     * 获取办事处数据列表
     */
    getOfficeName() {
      const _this = this
      getOfficeRef({ rows: 50 })
        .then(res => {
          if (res.success === 1) {
            _this.officeNameOption = res.data.records
            _this.disNameOption = []
            _this.shopNameOption = []
            _this.shopCallTel = []
          }
        })
    },
    /**
     * 获取经销商
     */
    getDisName(parentCode) {
      const _this = this
      let obj = {}
      if (parentCode === '') {
        // _this.initCustomerRef()
        _this.resetOfficeName()
        return
      }

      _this.resetDisName()

      obj = _this.officeNameOption.find((item) => {
        return item.code === parentCode
      })

      _this.amendData.officeName = obj.name

      getDealerInfo({ officeCode: obj.code })
        .then(res => {
          if (res.success === 1) {
            _this.disNameOption = res.data.records
          }
        })
    },
    /**
     * 获取门店信息
     */
    getShopName(parentCode) {
      const _this = this
      let obj = {}
      if (parentCode === '') {
        _this.resetDisName()
        return
      }

      _this.resetShopInfo()

      obj = _this.disNameOption.find((item) => {
        return item.code === parentCode
      })

      _this.amendData.disName = obj.name

      getOfficeDetail(parentCode).then(response => {
        const data = response.data
        if (Object.keys(data).length) {
          _this.amendData.officeCode = data.code
          _this.amendData.officeName = data.name
        }
      })

      getShopList(obj.id)
        .then(res => {
          if (res.success === 1) {
            _this.shopNameOption = res.data
          }
        })
    },
    disSelectChange(data) {
      this.resetShopInfo()
      if (data && data.code) this.checkShopNum(data.code)
    },
    selectChange(data) {
      if (data && data.shopCode) this.getSalesCall({ shopCode: data.shopCode })
    },
    // 查询该经销商下是否有门店
    checkShopNum(disCode) {
      const params = new FormData()
      params.append('page', 1)
      params.append('rows', 2)

      getMscInfoShop({ customerCodes: disCode }, params).then(res => {
        if (res.success === 1) {
          if (res.data.total === 0) {
            this.getSalesCall({ disCode: this.amendData.disCode })
          }
        }
      })
    },
    /**
     * 获取门店对应的联系方式
     */
    getSalesCall(obj) {
      if (Object.keys(obj).length === 0) {
        return
      }
      this.shopCallTel = []
      const paramsArr = ArrayFormat(obj)
      const pageInfo = new FormData()
      pageInfo.append('rows', 20)
      pageInfo.append('page', 1)
      if (Array.isArray(paramsArr) && paramsArr.length) pageInfo.append('filtersRaw', JSON.stringify(paramsArr))
      getShopAfterInfo(pageInfo).then(res => {
        if (res.success === 1) {
          const data = res.data.records
          data.forEach((item, index) => {
            if (item.contactPhone) {
              item.value = item.contactPhone
              item.name = item.afterSaleContact
            } else {
              data.splice(index, 1)
            }
          })
          if (Array.isArray(data) && data.length === 1) {
            this.amendData.afterSalesCall = data[0].value
          }
          this.shopCallTel = data
        } else {
          this.shopCallTel = []
        }
      })
    },
    /**
     * 匹配门店相应的联系方式
     */
    afterCallSearchAsync(queryString, callback) {
      const shopCallTel = this.shopCallTel
      const results = queryString ? shopCallTel.filter(this.createStateFilter(queryString)) : shopCallTel

      // setTimeout(() => {
      callback(results)
      // }, 3000 * Math.random())
    },
    /**
     * JS-filter Function
     */
    createStateFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },
    /**
     * 重置办事处以下信息
     */
    resetOfficeName() {
      const _this = this
      _this.$set(_this.amendData, 'officeCode', '')
      _this.$set(_this.amendData, 'officeName', '')
      _this.$set(_this.amendData, 'disCode', '')
      _this.$set(_this.amendData, 'disName', '')
      _this.$set(_this.amendData, 'shopCode', '')
      _this.$set(_this.amendData, 'shopName', '')
      _this.$set(_this.amendData, 'afterSalesCall', '')
      _this.disNameOption = []
      _this.shopNameOption = []
      _this.shopCallTel = []
    },
    /**
     * 重置经销商以下相关信息
     */
    resetDisName() {
      const _this = this
      _this.$set(_this.amendData, 'disCode', '')
      _this.$set(_this.amendData, 'disName', '')
      _this.$set(_this.amendData, 'shopCode', '')
      _this.$set(_this.amendData, 'shopName', '')
      _this.$set(_this.amendData, 'afterSalesCall', '')
      _this.shopNameOption = []
      _this.shopCallTel = []
    },
    /**
     * 重置门店信息
     */
    resetShopInfo() {
      const _this = this
      _this.$set(_this.amendData, 'shopCode', '')
      _this.$set(_this.amendData, 'shopName', '')
      _this.$set(_this.amendData, 'afterSalesCall', '')
      _this.shopCallTel = []
    },
    // 检查文件总大小
    checkFileSizeGt100() {
      let sumSize = 0
      this.imageList.forEach(e => {
        sumSize += e.size
      })
      // 限制100m
      if (sumSize > 100 * 1024 * 1024) {
        this.$message.error('上传文件总大小不能大于100M！')
        return true
      }
      return false
    },
    // 超时时，超时原因必填
    checkoutOverTimeReason() {
      if (Number(this.detailObj.isTimeoutOrder) === 1) {
        const status = /^\d+$/.test(this.amendData.overtimeReason)
        if (!status) {
          this.$message.error('请填写超时原因！')
        }
        return !status
      } else {
        return false
      }
    },
    // 判断赔付原因必填
    // checkCompensationCause() {
    //   const params = this.amendData
    //   if (([1, 2, 3].includes(Number(params.businessType1 || 0)) && Number(params.businessType2 || 0) === 15) ||
    //               (params.handleScheme && (params.handleScheme.includes(2) || params.handleScheme.includes('2')))) {
    //     if (!params.compensationCause || params.compensationCause.length === 0) {
    //       this.$message.warning('请选择赔付原因!')
    //       return true
    //     }
    //   }
    //   if (!params.urgencyDegree) {
    //     this.$message.warning('请选择紧急程度!')
    //     return true
    //   }
    //   if (Number(params.urgencyDegree || 0) === 2 || Number(params.urgencyDegree || 0) === 3) {
    //     if (!params.urgencyCause) {
    //       this.$message.warning('请填写紧急原因备注!')
    //       return true
    //     }
    //   }
    //   return false
    // },
    // 完结工单需判断处理方案必填,一级业务类型为投诉/纠纷(2)和业务办理（3）时必填
    // checkHandleScheme() {
    //   const params = this.amendData
    //   const businessType1 = Number(this.detailObj.businessType1 || 0)
    //   if (businessType1 !== 2 && businessType1 !== 3) {
    //     return false
    //   }
    //   if (!params.handleScheme || params.handleScheme.length === 0) {
    //     this.$message.warning('请选择处理方案!')
    //     return true
    //   }
    //   return false
    // },
    // 验证投诉原因必选（保存、派单、提交、完结的时候需要判断）
    // checkoutComplaintCause() {
    //   // 二级业务类型为44 产品质量 时，不必选
    //   if (Number(this.detailObj.businessType1) === 2 && Number(this.detailObj.businessType2 || 0) !== 44) {
    //     if (!this.amendData.complaintCause || this.amendData.complaintCause.length === 0) {
    //       this.$message.warning('请选择投诉原因')
    //       return true
    //     }
    //   }
    //   return false
    // },
    // 验证投诉类型必选（保存、派单、提交、完结的时候需要判断）
    // checkoutComplaintType() {
    //   if (Number(this.detailObj.businessType1) === 2) {
    //     if (!this.amendData.complaintType) {
    //       this.$message.warning('请选择投诉类型')
    //       return true
    //     }
    //   }
    //   return false
    // },
    // 验证赔付金额
    // checkoutCompensationFee() {
    //   const fee = this.amendData.compensationFee
    //   if (fee !== '' && fee != null && fee !== undefined) {
    //     if (!(/^(([1-9]{1}\d{0,9})|(0{1}))(\.\d{1,2})?$/.test(fee))) {
    //       this.$message.warning('请输入合法赔付金额，最多两位小数')
    //       return true
    //     }
    //   }
    //   return false
    // },
    // 验证二次费用必选(完结时需判断)
    // checkoutIsTwoCheckComputation() {
    //   if (Number(this.detailObj.businessType1 || 0) === 3 && [18, 19, 31, 32, 33].includes(Number(this.detailObj.businessType2 || 0))) {
    //     // 属于三方物流(经销商的所属办事处为6006)时,必选
    //     if (Number(this.detailObj.officeCode || 0) === 6006) {
    //       if ((this.amendData.isTwoCheckComputation !== 0 && this.amendData.isTwoCheckComputation !== '0') && (this.amendData.isTwoCheckComputation !== 1 && this.amendData.isTwoCheckComputation !== '1')) {
    //         this.$message.warning('请选择核算二次费用')
    //         return true
    //       }
    //     }
    //   }
    //   return false
    // },
    clearComplaintCause() {
      this.$set(this.amendData, 'complaintCause', [])
    },
    // 上报异常
    abnormalSuccess() {
      this.$set(this.bottomAuth, 'abnormal', true)
      this.reloadDetailInfo()
    },
    // 抄送
    carbonSuccess() {
      this.$set(this.bottomAuth, 'carbon', true)
      this.reloadDetailInfo()
    },
    /**
     * 保存工单详细
     */
    saveOrder() {
      if (!this.$refs.list.validate(true)) {
        return
      }
      if (this.checkFileSizeGt100()) {
        return
      }
      // if (this.checkoutOverTimeReason()) {
      //   return
      // }
      // if (this.checkCompensationCause()) {
      //   return
      // }
      // if (this.checkoutComplaintCause()) {
      //   return
      // }
      // if (this.checkoutComplaintType()) {
      //   return
      // }
      // if (this.checkoutCompensationFee()) {
      //   return
      // }
      const paramsObj = new FormData()
      const params = { ...this.amendData }
      // Object.keys(params).forEach(key => {
      //   if (params[key] === '') delete params[key]
      // })
      for (const file of this.imageList) {
        if (file) paramsObj.append('files', file)
      }

      params.content = `${params.content ? params.content : ''}`
      paramsObj.append('jsonStr', JSON.stringify(params))
      this.$msgbox({
        title: '保存工单',
        showCancelButton: true,
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning',
        message: '确定保存工单?'
      }).then(() => {
        this.saveLoading = true
        return postWorkOrderRecord(paramsObj).then(res => {
          if (res.success === 1) {
            this.$message({
              message: '工单保存成功',
              type: 'success'
            })
            this.$set(this.bottomAuth, 'save', true)
            this.reloadDetailInfo()
          }
        }).finally(() => { this.saveLoading = false })
      })
    },
    /**
     * 提交工单
     */
    submitOrder() {
      // 已完结工单提交时不做任何校验
      if (Number(this.detailObj.workOrderState || 0) !== 3) {
        if (!this.$refs.list.validate(true)) {
          return
        }
        // if (this.checkoutOverTimeReason()) {
        //   return
        // }
        // if (this.checkCompensationCause()) {
        //   return
        // }
        // if (this.checkoutComplaintCause()) {
        //   return
        // }
        // if (this.checkoutComplaintType()) {
        //   return
        // }
        // if (this.checkoutCompensationFee()) {
        //   return
        // }
        if (this.checkFileSizeGt100()) {
          return
        }
      }
      const paramsObj = new FormData()
      const params = { ...this.amendData }
      const contrast = { ...this.amendData }
      const txt = this.contrastData({ ...this.originalData }, contrast)
      // Object.keys(params).forEach(key => {
      //   if (params[key] === '') delete params[key]
      // })
      // 已完结工单可提交附件
      for (const file of this.imageList) {
        if (file) paramsObj.append('files', file)
      }
      params.content = `${txt}${params.content ? '留言内容：' + params.content : ''}`
      const { customerApplyStatus: applyStatus, workOrderState } = this.detailObj
      const status = ['02', '01'].includes(applyStatus) && ![3, '3'].includes(workOrderState)
      let tips = '0'
      const t = status ? this.$msgbox({
        title: '是否提醒商家',
        message: this.$createElement(WarnMerchant, {
          on: {
            change: v => { tips = v }
          },
          key: (new Date()).getTime()
        }),
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        showCancelButton: true
      }) : this.$msgbox({
        title: '提交工单',
        showCancelButton: true,
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning',
        message: '确定提交工单?'
      })

      t.then(() => {
        this.submitOrderLoading = true
        paramsObj.append('jsonStr', JSON.stringify(params))
        if (status) {
          paramsObj.append('tips', tips)
        }
        return putSubmit(paramsObj).then(res => {
          if (res.success === 1) {
            this.$message({
              message: '工单提交成功',
              type: 'success'
            })
            // 未关闭需求之前的写法
            // this.$set(this.bottomAuth, 'submit', true)
            // this.reloadDetailInfo()
            // =====
            this.$closePage()
          }
        })
      }).catch((e) => e).finally(() => { this.submitOrderLoading = false })
    },

    /**
     * 完结工单
     */
    finishOrder() {
      this.finishOrderLoading = true
      if (!this.$refs.list.validate(true)) {
        this.finishOrderLoading = false
        return
      }
      if (this.checkFileSizeGt100()) {
        this.finishOrderLoading = false
        return
      }
      // if (this.checkoutOverTimeReason()) {
      //   return
      // }
      // if (this.checkCompensationCause()) {
      //   return
      // }
      // if (this.checkHandleScheme()) {
      //   return
      // }
      // if (this.checkoutComplaintCause()) {
      //   return
      // }
      // if (this.checkoutComplaintType()) {
      //   return
      // }
      // if (this.checkoutCompensationFee()) {
      //   return
      // }
      // if (this.checkoutIsTwoCheckComputation()) {
      //   return
      // }

      const paramsObj = new FormData()
      const params = { ...this.amendData }
      // Object.keys(params).forEach(key => {
      //   if (params[key] === '') delete params[key]
      // })
      const contrast = { ...this.amendData }
      const txt = this.contrastData({ ...this.originalData }, contrast)
      params.content = `${txt}${params.content ? '留言内容：' + params.content : ''}`
      // params.content = ` 留言内容：${params.content ? params.content : '--'}`
      for (const file of this.imageList) {
        if (file) paramsObj.append('files', file)
      }
      paramsObj.append('jsonStr', JSON.stringify(params))
      this.$msgbox({
        title: '完结确认',
        showCancelButton: true,
        cancelButtonText: '返回修改',
        confirmButtonText: '确认无误',
        type: 'warning',
        message: '请确认当前<span style="color: red;">【处理方案】</span>是否准确！',
        dangerouslyUseHTMLString: true
      }).then(() => {
        return putFinish(paramsObj).then(res => {
          if (res.success === 1) {
            this.$message({
              message: '工单完结成功',
              type: 'success'
            })
            // 未关闭需求之前的写法
            // this.$set(this.bottomAuth, 'finish', true)
            // this.reloadDetailInfo()
            // =====
            this.$closePage()
            // this.closeCurrentTag()
          }
        })
      }).finally(() => { this.finishOrderLoading = false })
    },
    // 复制工单
    copyWorkOrder() {
      const { id, workOrderState } = this.detailObj
      this.$router.push({ name: 'CreateOrder', query: { id: id, state: workOrderState }})
    },
    // 关怀
    careHandle() {
      // FIXME: 关怀
      this.$msgbox({
        title: '关怀',
        showCancelButton: true,
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning',
        message: '是否确定生成关怀任务？'
      }).then(() => {
        this.$set(this.bottomAuth, 'care', true)
      })
    },
    // 上传附件成功
    onSuccessHandle(res, file, fileList) {
      // console.log(res, file, fileList)
    },
    // 文件改变时
    onChangeHandle(file, fileList) {
      this.imageList = fileList.map((list) => {
        return list.raw
      }).filter(e => {
        return e !== undefined
      })
    },
    // 完结工单不能删除
    onPreRemoveHandle(file, fileList) {
      if (this.detailObj.workOrderState === 3 && file.status === 'success') {
        return false
      } else {
        return true
      }
    },
    beforeRemoveHandle(file, fileList) {
      return this.$msgbox({
        title: '删除',
        message: '确认删除该附件？',
        showCancelButton: true,
        type: 'warning'
      }).then(() => {
        if (file.status === 'success') {
          const fileObj = { ...file }
          delete fileObj.name
          delete fileObj.url
          return deleteAnnex(fileObj).then(res => {
            this.$message({
              message: '附件删除成功',
              type: 'success'
            })
            return 'success'
          })
        }
      })
    },
    // 删除成功
    removeHandle(file, fileList) {
      this.imageList = fileList.map((list) => {
        return list.raw
      }).filter(e => {
        return e !== undefined
      })
    },
    // 删除附件
    // onRemoveHandle(file, fileList) {
    //   if (file.status === 'success') {
    //     const fileObj = { ...file }
    //     delete fileObj.name
    //     delete fileObj.url
    //     deleteAnnex(fileObj).then(res => {
    //       if (res.success === 1) {
    //         this.$message({
    //           message: '附件删除成功',
    //           type: 'success'
    //         })
    //         this.imageList = fileList.map((list) => {
    //           return list.raw
    //         }).filter(e => {
    //           return e !== undefined
    //         })
    //       }
    //     })
    //   }
    // },
    // 关闭当前Tag
    closeCurrentTag() {
      this.$closePage()
    },
    // 改派
    receiveSinga(val) {
      if (Array.isArray(val)) {
        this.receiveSystem = val
        this.reloadDetailInfo()
      }
    },
    // 验证是否允许打开催办
    checkIsOpenUrge() {
      return new Promise((resolve, reject) => {
        if (this.checkoutOverTimeReason()) {
          return reject('超时原因未填！')
        }
        return resolve()
      })
    },
    // 催办成功
    handleUrgeSuccess() {
      this.$set(this.bottomAuth, 'urge', true)
      this.reloadDetailInfo()
    },
    // 关怀成功后
    careSuccess(data) {
      // TODO: 关怀后记录关怀流水
    },
    // 改派成功后执行
    receiveSuccess(data) {
      if (data.receiveDeptNames && data.receiveDeptNames.length > 0) {
        this.$set(this.detailObj, 'receiveDeptNames', data.receiveDeptNames)
        delete data.receiveDeptNames
      }
      this.amendData = { ...this.amendData, ...data }
      this.$set(this.bottomAuth, 'receive', true)
      this.reloadDetailInfo()
    },
    // 刷新工单流水
    reloadDetailInfo() {
      getByIdWorkOrderRecord(this.id).then(async(res) => {
        if (res.success === 1) {
          const data = { ...res.data }
          if (Object.keys(data).indexOf('receiveSystem') !== -1) this.receiveSystem.push(data.receiveSystem)
          if (Object.keys(data).indexOf('ccSystem') !== -1) this.ccSystem.push(data.ccSystem)
          this.$set(this.amendData, 'workOrderState', data.workOrderState)
          this.$set(this.detailObj, 'workOrderState', data.workOrderState)
          this.processingList = data.processingList
        }
      })
    },
    // 对比两对象差异值
    contrastData(o, n) {
      if (typeof o !== 'object') o = { ...this.originalData }
      const fm = {
        complaintCause: '投诉原因',
        complaintType: '投诉类型',
        returnsCause: '退换货原因',
        bpmDeptName: '业务部门',
        compensationCause: '赔付原因',
        /* officeName: '办事处',
        disName: '经销商',
        shopName: '门店',
        afterSalesCall: '售后联系人电话', */
        urgencyDegree: '紧急程度',
        urgencyCause: '紧急原因备注',
        overdueReason: '超期原因',
        overtimeReason: '超时原因',
        processingDeadline: '处理截止日期',
        timeoutReason: '处理时效',
        nextHandlerName: '处理人',
        handleScheme: '处理方案',
        paymentMode: '支付方式',
        compensationFee: '赔付金额',
        gift: '赠品名称',
        deliveryNeed: '送装需求',
        bookingServiceTime: '预约送装服务时间',
        processRate: '维修进度',
        patchCode: '补件单号',
        isTwoCheckComputation: '核算二次费用',
        isPatchOverdue: '是否补件超期'
      }
      const fmCode = {
        compensationCause: this.compensationCauseOp || [],
        complaintCause: this.complaintCauseStore || [],
        complaintType: this.complaintTypeOp || [],
        returnsCause: this.returnsCauseOp || [],
        urgencyDegree: this.urgencyDegreeOp || [],
        overdueReason: this.overdueReasonOp || [],
        overtimeReason: this.overtimeReasonOp || [],
        timeoutReason: this.timeoutReasonOp || [],
        handleScheme: this.handleSchemeOp || [],
        paymentMode: this.paymentModeOp || [],
        deliveryNeed: this.deliveryNeedOp || [],
        processRate: this.processRateOp || [],
        isTwoCheckComputation: this.YesOrNoList || [],
        isPatchOverdue: this.YesOrNoList || []
      }
      const multipleKeys = ['compensationCause', 'complaintCause', 'handleScheme', 'paymentMode'] // 多选字段
      let changTxt = ''
      if (typeof o === 'object' && typeof n === 'object') {
        Object.keys(o).forEach(k => {
          if (k === 'content') return
          if (multipleKeys.includes(k)) {
            // 判断多选字段是否变更
            const isEq = o[k].length === n[k].length && o[k].every(v => {
              const f = n[k].some(j => j === v)
              return f
            })
            if (isEq) return
            if (fm[k]) {
              const oName = []
              const nName = []
              if (Array.isArray(fmCode[k]) && fmCode[k].length) {
                for (const item of o[k]) {
                  const tmp = fmCode[k].find(v => v.dictCode === item || v.dictTypeCode === `${item}`)
                  if (tmp && tmp.dictName) {
                    oName.push(tmp.dictName)
                  } else {
                    oName.push(o[k])
                  }
                }
                for (const item of n[k]) {
                  const tmp = fmCode[k].find(v => v.dictCode === item || v.dictTypeCode === `${item}`)
                  if (tmp && tmp.dictName) {
                    nName.push(tmp.dictName)
                  } else {
                    nName.push(n[k])
                  }
                }
                o[k] = oName.join(',')
                n[k] = nName.join(',')
              }
              if (o[k]) {
                changTxt += `${fm[k]}：【${o[k]}】修改为【${n[k] || '空'}】；`
              } else if (n[k] !== undefined) {
                if (k === 'compensationFee' && (n[k] === 0 || n[k] === '0')) {
                  // 解决 赔付金额：新增为【0】
                } else {
                  changTxt += `${fm[k]}：新增为【${n[k]}】；`
                }
              }
            }
            return
          }
          if (o[k] !== n[k]) {
            if (fm[k]) {
              if (Array.isArray(fmCode[k]) && fmCode[k].length) {
                for (const item of fmCode[k]) {
                  if (item.dictCode === o[k]) o[k] = item.dictName
                  if (item.dictCode === n[k]) n[k] = item.dictName
                }
              }
              if (o[k]) {
                changTxt += `${fm[k]}：【${o[k]}】修改为【${n[k] || '空'}】；`
              } else if (n[k] !== undefined) {
                if (k === 'compensationFee' && (n[k] === 0 || n[k] === '0')) {
                  // 解决 赔付金额：新增为【0】
                } else {
                  changTxt += `${fm[k]}：新增为【${n[k]}】；`
                }
              }
            }
          }
        })
      }
      return changTxt
    },
    scalarArrayEquals(array1, array2) {
      return array1.length === array2.length && array1.every((v, i) => v === array2[i])
    },
    // 客户联系电话  发送短信
    contactTpSms(telPhone) {
      const callTel = (telPhone || '').trim()
      const workOrderCode = ''
      const content = ''
      this.$router.push({ name: 'SMSSend', query: { callTel, workOrderCode, content }})
    },
    // 短信发送
    toSms(afterSalesCall) {
      const callTel = (afterSalesCall || '').trim()
      const provinceName = this.detailObj.provinceName || ' '
      const cityName = this.detailObj.cityName || ' '
      const countyName = this.detailObj.countyName || ' '
      const streetName = this.detailObj.streetName || ' '
      const detailAddress = this.detailObj.detailAddress || ' '
      const contactName = this.detailObj.contactName || ' '
      const contactPhone = this.detailObj.contactPhone || ' '
      const workOrderCode = this.detailObj.workOrderCode || ' '
      const content = `工单编号：${workOrderCode}，客户姓名：${contactName}，联系电话：${contactPhone}，客户地址：${provinceName}${cityName}${countyName}${streetName}${detailAddress}`
      if (!callTel) {
        this.$message.info('暂无售后联系电话号码！')
        return
      }
      this.$router.push({ name: 'SMSSend', query: { callTel, workOrderCode, content }})
    },
    // 外呼
    callOutHandle(phone) {
      if (!phone) {
        this.$message.info('没有电话号码！')
        return
      }
      this.$refs.callOut.debounceCallOut(phone).then(recordId => {
        console.log('通话记录id: ', recordId)
        this.recordId = recordId
      })
    },
    // 查询补件单号对应的列表
    handleSearchPatchOrder() {
      const codes = this.patchCode.trim().replace(/，/g, ',').split(',').filter(v => !!v)
      if (codes.length === 0) {
        this.patchCode = ''
        this.$message.warning('请输入补件单号')
        return
      }
      const patchCodeList = this.amendData.patchCode ? this.amendData.patchCode.split(',').filter(v => v !== '') : []
      const pbillIds = Array.from(new Set([...patchCodeList, ...codes]))
      this.$set(this.amendData, 'patchCode', pbillIds.join(','))

      this.$nextTick(() => {
        this.$refs.billList.getData()
      })
    },
    // 补件查询结果变更
    billChange(data) {
      this.patchCode = ''
      const pbillIds = data.map(v => v.auditCode).join(',')
      this.$set(this.amendData, 'patchCode', pbillIds)
    },
    handlerInvalidReturn() {
      return this.$msgbox({
        title: '提示',
        message: '确认退回?',
        type: 'warning',
        showCancelButton: true
      }).then(() => {
        return invalidReturnApplyStatus(this.detailObj.id, '01').then(res => {
          this.$message.success('操作成功!')
          this.InvalidReturnButton = true
        })
      })
    },
    handleAudit() {
      // 客诉审核
      // let url = `https://uipdev.quanyou.com.cn/myiframe/urlPath?src=%2Fec-delivery-service%2Fdistricenter&name=%E9%85%8D%E9%80%81%E4%BB%BB%E5%8A%A1%E7%AE%A1%E7%90%86&menuCode=PC3336005&ecCode=${this.detailObj.ecCode}`
      // if (!this.$dev) {
      //   url = `https://uip.quanyou.com.cn/myiframe/urlPath?src=%2Fec-delivery-service%2Fdistricenter&name=%E9%85%8D%E9%80%81%E4%BB%BB%E5%8A%A1%E7%AE%A1%E7%90%86&menuCode=PC3336005&ecCode=${this.detailObj.ecCode}`
      // }
      // window.open(url, '_blank')
      this.$router.push(`/myiframe/urlPath?src=%2Fec-delivery-service%2Fdistricenter&name=%E9%85%8D%E9%80%81%E4%BB%BB%E5%8A%A1%E7%AE%A1%E7%90%86&menuCode=PC3336005&ecCode=${this.detailObj.ecCode}`)
    },
    // 只有购买渠道为电商才有售后退货
    // 过滤退换货原因
    filterHandleScheme(data) {
      return data.filter(e => {
        if ([14, '14'].includes(e.dictCode) && ![1, '1'].includes(this.detailObj.buyChannel)) {
          return false
        }
        return true
      })
    },
    // 获取配送信息
    getDeliveryInfo(codes) {
      queryDeliveryBySources(codes).then(res => {
        this.deliveryInfo = res.data
      })
    }
  }
}
</script>
<style lang='scss' scoped>
.details{

}
.details .content-wrap {
  padding: 10px 25px;
}
.details .content-wrap /deep/ .el-row .el-col {
  line-height: 38px;
}
.details .content-wrap /deep/ .el-row .custom-list-item {
  margin-bottom: 0;
}
.details .content-wrap /deep/ .el-row .custom-list-item .label-style {
  text-align-last: right;
}
.details .content-wrap /deep/ .el-row .custom-list-item span:first-child {
  // width: 90px;
  font-size: 12px;
  text-align: right;
}
.details .content-wrap /deep/ .el-row .custom-list-item span:last-child {
  font-size: 12px;
}
.details .content-wrap .el-row .afterCall {
  overflow: inherit !important;
}
.details {
  /deep/ .el-autocomplete {
    width: 100%;
  }
  /deep/ .my-autocomplete {
    & li {
      display: flex;
      justify-content: space-between;
      padding: 10px;
      padding: 7px;

      .tel {
        text-overflow: ellipsis;
        overflow: hidden;
      }
      .name {
        font-size: 12px;
        color: #b4b4b4;
      }
      .highlighted .name {
        color: #ddd;
      }
    }
  }
}
.details .content-wrap /deep/ .call-detail {
  line-height: 24px;
}
.details .content-wrap /deep/ .custom-title {
  padding: 0;
}
.details .content-wrap /deep/ .order-top {
  // padding-top: 30px;
}
.details .content-wrap /deep/ .custom-title h3 {
  font-weight: bold;
  font-size: 14px;
  color: #16BC83;
}
.details .content-wrap /deep/ .order-list {
  line-height: 18px;
}

.details .content-wrap /deep/ .order-list p:first-child {
  width: 20%;
  flex: 0 0 20% !important;
}
.details .content-wrap /deep/ .order-list p:nth-child(2) {
  width: 20%;
  flex: 0 0 20% !important;
}
.details .content-wrap /deep/ .order-list p:nth-child(3) {
  width: 37%;
  flex: 0 0 37% !important;
}
.details .content-wrap /deep/ .order-list p:last-child {
  width: 15%;
  flex: 0 0 15% !important;
}
// 短信图标
.sms{
  color:#00926d;
  cursor: pointer;
}
</style>
<style lang="scss">
  .noneTick{
    & [class*="el-button el-picker-panel__link-btn el-button--text el-button--mini"]{
      display: none;
    }
  }
  .details{
    [class*="el-input-group__append"]{
      padding: 0 5px !important;
    }
  }
</style>
